package com.yehuo.app.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yehuo.app.entity.BanUser;
import com.yehuo.app.entity.Page;
import com.yehuo.app.entity.User;
import com.yehuo.app.entity.Wallet;
import com.yehuo.app.mapper.BanUserMapper;
import com.yehuo.app.mapper.UserMapper;
import com.yehuo.app.model.R;
import com.yehuo.app.model.Result;
import com.yehuo.app.util.APiUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private BanUserMapper banUserMapper;

    /**
     * 注册/更新用户
     */
    @RequestMapping("/create")
    public R<Integer> dd(@RequestBody User user) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", user.getUid());
        map.put("name", user.getName());
        map.put("displayName", user.getNickname());
        map.put("portrait", user.getAvatar());
        map.put("mobile", user.getMobile());
        map.put("email", user.getEmail());
        map.put("address", user.getAddress());
        map.put("company", user.getCompany());
        map.put("extra", user.getExtra());
        map.put("gender", user.getGender());
        map.put("password","123456");//初始化密码
        Result data = APiUtil.getData("admin/user/create", map);
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(data.getCode() == 0 ? "添加成功" : data.getMsg());
        return result;
    }

    /**
     * 设置密码
     */
    @Deprecated
    @RequestMapping("/setPw")
    public R<Integer> pw( User user) {
        userMapper.update(user, new UpdateWrapper<User>().eq("_name",user.getName()));
        return new R<>();
    }

    /**
     *
     */
    @RequestMapping("/getUserByName")
    @Deprecated
    public R<User> getUserByName( User user) {
        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("_name", user.getName()));
        if(users.isEmpty()){
            return new R<User>(0,users);
        }
        return new R<>(0,users);
    }
    /**
     * 由于im服务器不返回面，单独获取用户密码
     */
    @RequestMapping("/getPasswordByUserId")
    public R<Integer> getPasswordByUserId(String userId) {
        String passwordByUId = userMapper.selectPasswordByUId(userId);
        R<Integer> result = new R<>();
        if(StringUtils.isEmpty(passwordByUId)){
            result.setCode(1);
        }else{
            result.setCode(0);
        }
        result.setMsg(passwordByUId);
        return result;
    }
    /**
     * 获取用户
     */
    @RequestMapping("/getUser")
    public R<Integer> getUserOrCreateUser(@RequestBody User user) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", user.getUid());
        map.put("name", user.getName());
        map.put("displayName", user.getNickname());
        map.put("portrait", user.getAvatar());
        map.put("mobile", user.getMobile());
        map.put("email", user.getEmail());
        map.put("address", user.getAddress());
        map.put("company", user.getCompany());
        map.put("extra", user.getExtra());
        map.put("gender", user.getGender());
        Result data = APiUtil.getData("admin/user/create", map);
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(data.getCode() == 0 ? "添加成功" : data.getMsg());
        return result;
    }

    /**
     * 获取用户列表
     *
     * @param page
     * @return
     */
    @RequestMapping("/list")
    public R<User> list(Page page, User user) {
        QueryWrapper queryWrapper = null;
        /**
         * 如果搜索关键字为空
         */
        boolean flag = StrUtil.isEmpty(user.getSearch());
        if (!flag) {
            queryWrapper = new QueryWrapper();
            queryWrapper.like("_name", user.getSearch());
            queryWrapper.or();
            queryWrapper.like("_mobile", user.getSearch());
            queryWrapper.or();
            queryWrapper.like("_display_name", user.getSearch());
        }
        //开启分页
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<User> list = userMapper.selectList(queryWrapper);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        R<User> result = new R<User>((int) pageInfo.getTotal(), pageInfo.getList());
        return result;
    }

    /**
     * 获取封禁用户列表
     *
     * @return
     */
    @RequestMapping("/ban/list")
    public R<BanUser> banList(Page page) {
        //开启分页
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<BanUser> list = banUserMapper.selectList(null);
        list.forEach(o -> {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("_uid", o.getUid());
            User user = userMapper.selectOne(queryWrapper);
            o.setNickname(user.getNickname());
        });
        PageInfo<BanUser> pageInfo = new PageInfo<>(list);
        R<BanUser> r = new R<BanUser>((int) pageInfo.getTotal(), pageInfo.getList());
        return r;
    }

    /**
     * 解封
     *
     * @return
     */
    @RequestMapping("/unban/{uid}")
    public R<Integer> unBan(@PathVariable("uid") String uid) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", uid);
        map.put("status", 0);
        Result result = APiUtil.getData("/admin/user/update_block_status", map);
        R<Integer> r = new R<>();
        r.setCode(result.getCode());
        r.setMsg("success".equals(result.getMsg()) ? "解封成功" : "解封失败");
        return r;

    }

    /**
     * 封禁
     *
     * @return
     */
    @RequestMapping("/ban/{uid}")
    public R<Integer> ban(@PathVariable("uid") String uid) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", uid);
        map.put("status", 2);
        Result result = APiUtil.getData("/admin/user/update_block_status", map);
        R<Integer> r = new R<>();
        r.setCode(result.getCode());
        r.setMsg("success".equals(result.getMsg()) ? "封禁成功" : "封禁失败");
        return r;
    }

    /**
     * 发送消息
     */
    @RequestMapping("/send/message")
    public R<Integer> sendMessage(@RequestBody HashMap<String, Object> parameter) {
        Map<String, Object> map = new HashMap<>();
        //发送者用户ID
        map.put("sender", "admin");
        //群发目标ID
        List<String> users = new ArrayList<>();
        users.add((String) parameter.get("target"));
        map.put("targets", users);
        Map<String, Object> payload = new HashMap<>();
        payload.put("type", 1);
        payload.put("searchableContent", parameter.get("content"));
        map.put("payload", payload);
        Result result = APiUtil.getData("admin/message/multicast", map);
        R<Integer> r = new R<>();
        r.setCode(result.getCode());
        r.setMsg("success".equals(result.getMsg()) ? "发送成功" : result.getMsg());
        return r;
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @RequestMapping("/update/password")
    public R<Integer> updateUserPassword(@RequestBody User user) {
        R<Integer> r = new R<>();
        String oldPassword = user.getOldPassword();
        String newPassword = user.getNewPassword();
        /**
         * 查询用户信息
         */
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("_passwd_md5", SecureUtil.md5(oldPassword));
        queryWrapper.eq("_uid", "admin");
        User userInfo = userMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            r.setCode(999);
            r.setMsg("原密码不正确");
            return r;
        } else {
            user.setId(userInfo.getId());
            //设置新密码
            user.setPassword(SecureUtil.md5(user.getNewPassword()));
            userMapper.updateById(user);
            r.setCode(0);
            r.setMsg("修改成功");
            return r;
        }


    }

    /**
     * 修改用户手机号
     *
     * @return
     */
    @RequestMapping("/update/phone")
    public R<Integer> updateUserPhone(@RequestBody User user) {
        R<Integer> r = new R<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("_uid", "admin");
        User userInfo = userMapper.selectOne(queryWrapper);
        user.setId(userInfo.getId());
        int i = userMapper.updateById(user);
        r.setCode(i > 0 ? 0 : 999);
        r.setMsg(i > 0 ? "修改成功" : "修改失败");
        return r;
    }

    /**
     * 修改用户手机号
     *
     * @return
     */
    @RequestMapping("/query/phone")
    public R<Integer> queryUserPhone() {
        R<Integer> r = new R<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("_uid", "admin");
        User userInfo = userMapper.selectOne(queryWrapper);
        r.setCode(0);
        r.setMsg("成功");
        Map<String, Object> map = new HashMap<>();
        map.put("phone", userInfo.getMobile());
        r.setMap(map);
        return r;
    }

    /**
     * 查询用户头像
     *
     * @return
     */
    @RequestMapping("/query/avatar")
    public R<Integer> queryUserAvatar() {
        R<Integer> r = new R<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("_uid", "admin");
        User userInfo = userMapper.selectOne(queryWrapper);
        r.setCode(0);
        r.setMsg("成功");
        Map<String, Object> map = new HashMap<>();
        map.put("avatar", userInfo.getAvatar());
        r.setMap(map);
        return r;
    }


}
